package supercafe.core;

import java.util.Vector;
import supercafe.dataprovider.DataGetter;
import supercafe.dataprovider.FinishGet;
import supercafe.defines.URLs;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;

public class ViewOrderScreen extends ListActivity implements FinishGet, OnClickListener {

	protected DataGetter dataGetter = new DataGetter(this,this);
	
	protected Vector<OrderItem> listItems;
	protected ViewOrderItemAdapter adap;
	
	protected int employeeId;
	protected int tableId = 1;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        tableId = this.getIntent().getIntExtra("tableId", 1);
        
        setContentView(R.layout.view_order_screen);
        listItems = new Vector<OrderItem>();
        
        Button btnBack = (Button) findViewById(R.id.btnCancel_ViewOrder);
        btnBack.setOnClickListener(this);
        
        Runnable getListItems = new Runnable(){
            @Override
            public void run() {
            	getListItemsOfTable(tableId);
            }
        };
        Thread thread =  new Thread(null, getListItems, "GetMenuItems-MagentoBackground");
        thread.start();
        adap = new ViewOrderItemAdapter(this, R.layout.list_view_order_items_row, listItems);
        setListAdapter(adap);
    }
    
    private Runnable notifyAdapter = new Runnable() {
        @Override
        public void run() {
            if(listItems != null && listItems.size() > 0 && adap!=null){
            	adap.notifyDataSetChanged();
            }
        }
    };
        
    private void getListItemsOfTable(int id) {
		// TODO Auto-generated method stub
		dataGetter.execute(URLs.GET_ORDER_OF_TABLE + id);		
	}
        
	public void onNothingSelected(AdapterView<?> arg0) {}
	
	public void onClick(View v) {
		// TODO Auto-generated method stub
		//go to appreciated menu
    	try{
    		int id = v.getId();
    		switch(id){
    			case R.id.btnCancel_ViewOrder:
    				Intent returnToTaskScreenIntent = new Intent();
    				setResult(Activity.RESULT_CANCELED, returnToTaskScreenIntent);
    				ViewOrderScreen.this.finish();
    				break;
    		}
    	}catch(Exception e){
    		Log.e("exception-tag",e.getMessage());
    	}
	}

	@Override
	public void doFinishGet() {
		// TODO Auto-generated method stub
		String employeeName = null; int totalPrice = 0;
		
		String result = dataGetter.getResponseResult();
		listItems = XMLHandler.getListItems(this,result,listItems);
		employeeName = XMLHandler.getEmployeeName(result);
		totalPrice = XMLHandler.getTotalPrice(result);
		runOnUiThread(notifyAdapter);
		
		TextView tvEmployeeName = (TextView) findViewById(R.id.tvEmployeeName_ViewOrder);
		tvEmployeeName.setText("NVPV : "+employeeName);
		TextView tvTotalPrice = (TextView) findViewById(R.id.tvTotalPrice_ViewOrder);
		tvTotalPrice.setText("Tổng tiền : "+totalPrice);
	}

	
}

class ViewOrderItemAdapter extends BaseAdapter implements Filterable, OnClickListener{
    
	private LayoutInflater mInflater;
    private Context context;
	private Vector<OrderItem> listItems;
	private int position = 0;
	
	private int layoutId;
	    
    public ViewOrderItemAdapter(Context context, int layoutId, Vector<OrderItem> list) {
	      // Cache the LayoutInflate to avoid asking for a new one each time.
	      mInflater = LayoutInflater.from(context);
	      this.context = context;
	      this.layoutId = layoutId;
	      listItems = list;
	}

	public Vector<OrderItem> getListItems() {
		return this.listItems;
	}
    public View getView(final int position, View convertView, ViewGroup parent) {
      // A ViewHolder keeps references to children views to avoid
      // unnecessary calls
      // to findViewById() on each row.
    	//Toast.makeText(this.context, "getView - position = "+position, 3000).show();
      ViewHolder_ViewOrder holder;
      
      // When convertView is not null, we can reuse it directly, there is
      // no need
      // to re-inflate it. We only inflate a new View when the convertView
      // supplied
      // by ListView is null.
      if (convertView == null) {
        convertView = mInflater.inflate(layoutId, null);
        convertView.setFocusable(false);
        // Creates a ViewHolder and store references to the two children
        // views
        // we want to bind data to.
        holder = new ViewHolder_ViewOrder();
        holder.itemName = (TextView) convertView.findViewById(R.id.itemName_ViewOrder);
        holder.itemPrice = (TextView) convertView.findViewById(R.id.itemPrice_ViewOrder);
        holder.itemQuanlity = (TextView) convertView.findViewById(R.id.itemQuanlity_ViewOrder);
        
        //convertView.setOnClickListener(this);
        holder.itemName.setOnClickListener(this);
        holder.itemQuanlity.setOnClickListener(this);
        holder.itemPrice.setOnClickListener(this);
        
        
        convertView.setTag(holder);
      } else {
        // Get the ViewHolder back to get fast access to the TextView
        // and the ImageView.
        holder = (ViewHolder_ViewOrder) convertView.getTag();
        
      }

      // Bind the data efficiently with the holder.
      
      holder.itemName.setText(listItems.get(position).getItemName());
      int q = listItems.get(position).getQuanlity();
      holder.itemQuanlity.setText((q<10?"0":"")+q);
      holder.itemPrice.setText(""+listItems.get(position).getItemPrice());
      
      holder.itemName.setTag(position);
      holder.itemQuanlity.setTag(position);
      holder.itemPrice.setTag(position);

      return convertView;
    }
    
    

      public android.widget.Filter getFilter() {
        return null;
      }

      public long getItemId(int position) {
    	  //Toast.makeText(this.context, "getItemId - position = "+position, 3000).show();
    	  if(listItems.isEmpty()) return 0;
    	  return listItems.get(position).getItemId();
    	//return position;
      }

      public int getCount() {
    	  //Toast.makeText(this.context, "getCount - listItems.size() = "+listItems.size(), 3000).show();
        return listItems.size();
      }

      public Object getItem(int position) {
    	//Toast.makeText(this.context, "getItem - position = "+position, 3000).show();
    	
        return listItems.get(position);
      }

	public void onClick(View v) {
		
		try{
			// TODO Auto-generated method stub
			position = (Integer) v.getTag();
			
			if(!listItems.get(position).getNote().equals(""))
				Toast.makeText(this.context, listItems.get(position).getItemName()+
						"\n#Số lượng: "+listItems.get(position).getQuanlity()+
						"\n#Ghi chú: "+listItems.get(position).getNote(),
						2000).show();
			else
				Toast.makeText(this.context, listItems.get(position).getItemName()+
						"\n#Số lượng: "+listItems.get(position).getQuanlity()+
						"\n#Ghi chú: Không có",
						1200).show();
			
		}catch(Exception e){
			//Toast.makeText(this.context, "exception = "+e.getMessage() +"\n"+e.getStackTrace()[0].toString()+"\n"+"\n"+e.getStackTrace()[1].toString()+"\n"+"\n"+e.getStackTrace()[2].toString()+"\n"+"\n"+e.getStackTrace()[3].toString()+"\n", 3000).show();
			e.printStackTrace();
		}
	}

	public void addViewOrderItem(OrderItem orderItem) {
		// TODO Auto-generated method stub
		this.listItems.add(orderItem);
	}
}

class ViewHolder_ViewOrder {
    TextView itemName;
    TextView itemQuanlity;
    TextView itemPrice;
}
